/*
CREATE TABLE ski_logs (
 id SERIAL PRIMARY KEY,
 user_id varchar(255),
 app_version varchar(255),
 level varchar(255),
 message TEXT NOT NULL,
 timestamp timestamptz(6),
 ios_version varchar(255),
 created_at timestamptz(6)
);
*/

const Router = require("@koa/router");
const { Pool } = require("pg");
const router = new Router({ prefix: "/ski-logs" });
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 上传日志接口
router.post("/", async (ctx) => {
  try {
    const { user_id, app_version, ios_version, level, message, timestamp } = ctx.request.body;

    if (message.includes("未找到存储的个人信息")){
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "排除异常信息"
      };
      return;
    }
    
    // 验证必填字段
    if (!user_id || !level || !message) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "缺少必填字段：user_id, level, message"
      };
      return;
    }
    
    // 验证日志级别
    const validLevels = ['info', 'warn', 'error'];
    if (!validLevels.includes(level)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "日志级别必须是 info, warn 或 error 之一"
      };
      return;
    }
    
    // 检查是否与上一条日志重复
    const lastLogResult = await pool.query(
      "SELECT user_id, app_version, ios_version, level, message FROM ski_logs WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1",
      [user_id]
    );
    
    if (lastLogResult.rows.length > 0) {
      const lastLog = lastLogResult.rows[0];
      if (lastLog.user_id === user_id && 
          lastLog.app_version === app_version && 
          lastLog.ios_version === ios_version && 
          lastLog.level === level && 
          lastLog.message === message) {
        ctx.status = 444;
        ctx.body = {
          success: false,
          message: "重复的日志内容，已忽略"
        };
        return;
      }
    }
    
    // 插入日志到数据库
    const result = await pool.query(
      "INSERT INTO ski_logs (user_id, app_version, ios_version, level, message, timestamp) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
      [user_id, app_version, ios_version, level, message, timestamp || new Date()]
    );
    
    console.log(`${new Date().toLocaleString()} 日志已保存:`, {
      id: result.rows[0].id,
      user_id,
      level,
      message: message.substring(0, 100) + (message.length > 100 ? '...' : '')
    });
    
    ctx.body = {
      success: true,
      message: "日志上传成功",
      data: {
        id: result.rows[0].id,
        created_at: result.rows[0].created_at
      }
    };
    
  } catch (err) {
    console.error(`${new Date().toLocaleString()} 日志上传失败:`, err);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "服务器内部错误"
    };
  }
});

module.exports = router;